package cn.iocoder.yudao.module.product.service.sku;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.module.digital.api.cardkeyproduct.CardkeyProductApi;
import cn.iocoder.yudao.module.digital.api.cardkeyproduct.dto.CardkeyProductDTO;
import cn.iocoder.yudao.module.digital.enums.cardkeysecret.CardKeySourceEnum;
import cn.iocoder.yudao.module.product.constant.ProductConstant;
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSkuSaveReqV2VO;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.product.enums.spu.DeliveryMethodEnum;
import cn.iocoder.yudao.module.product.enums.spu.ProductSkuStatusEnum;
import cn.iocoder.yudao.module.product.enums.spu.ProductSpuStatusEnum;
import cn.iocoder.yudao.module.product.util.ProductUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Description:
 * Author: li
 * Date: 2024/3/28
 */
@Service
@Slf4j
public class GiftCardSkuServiceImpl implements IGiftCardSkuService {
    @Lazy
    @Resource
    private CardkeyProductApi cardkeyProductApi;
    @Resource
    private ProductSkuService productSkuService;

    @Override
    public void checkCreateOrUpdateSku(ProductSkuSaveReqV2VO createReqVO, ProductSpuDO spu, boolean create) {
        // 礼品卡类型
        final DeliveryMethodEnum deliveryMethodEnum = checkBasicNullValue(createReqVO);

        if (deliveryMethodEnum == DeliveryMethodEnum.AUTOMATIC) {
            // 自动发货
            final CardkeyProductDTO cardkeyProductDTO = checkAutoMatic(createReqVO, spu);
            if (create) {
                final CardKeySourceEnum cardKeySourceEnum = CardKeySourceEnum.fromValue(cardkeyProductDTO.getSource());
                if (cardKeySourceEnum == CardKeySourceEnum.MANUAL) {
                    // 采购发货,使用cdk的库存
                    //final Long cdkStock = cardkeyProductApi.getStock(cardkeyProductDTO.getProductNo());
                    //createReqVO.setStock(cdkStock.intValue());
                    createReqVO.setStock(ProductConstant.STOCK_MAX);
                } else {
                    // api发货
                    createReqVO.setStock(ProductConstant.STOCK_MAX);
                }
            }
        } else {
            // 手动发货
            if (create) {
                createReqVO.setStock(ProductConstant.STOCK_MAX);
            }
            checkManual(createReqVO);
        }
    }

    // 手动发货
    private static void checkManual(ProductSkuSaveReqV2VO createReqVO) {
//        if (createReqVO.getCustomDenomination()) {
//            log.warn("手动发货，不能自定义面值");
//            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "手动发货，不能自定义面值");
//        }

//        // 售价不能低于固定面值
//        final Integer denominationFixed = createReqVO.getDenominationFixed();
//        final Integer price = createReqVO.getPrice();
//        if (price < denominationFixed) {
//            log.warn("售价不能低于固定面值, price = {}, denominationFixed = {}", price, denominationFixed);
//            //throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "售价不能低于固定面值");
//        }
    }

    // 自动发货
    private CardkeyProductDTO checkAutoMatic(ProductSkuSaveReqV2VO createReqVO, ProductSpuDO spu) {
        ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "cardKeyProductNo"); // 卡密商品编号
        final String cardKeyProductNo = createReqVO.getCardKeyProductNo();
        final CardkeyProductDTO cardKeyProduct = cardkeyProductApi.getCardKeyProductByNo(cardKeyProductNo);

        if (cardKeyProduct == null) {
            log.warn("卡密商品不存在, cardKeyProductNo = {}", cardKeyProductNo);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, String.format("卡密商品不存在 [%s]", cardKeyProductNo));
        }

        if (!cardKeyProduct.getCurrencyCode().equals(spu.getCurrencyCode())) {
            log.warn("卡密商品货币代码跟SPU不一致, cardKeyProductNo = {}, card.currencyCode = {}, spu.currencyCode = {}",
                    cardKeyProductNo, cardKeyProduct.getCurrencyCode(), spu.getCurrencyCode());
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, String.format("卡密商品货币代码跟SPU不一致 [%s]", cardKeyProductNo));
        }

        if (createReqVO.getId() != null) {
            // 更新
            final ProductSkuDO sku = productSkuService.getSku(createReqVO.getId());
            final String oldCardKeyProductNo = sku.getCardKeyProductNo();
            if (ProductSpuStatusEnum.isEnable(spu.getStatus()) && ProductSkuStatusEnum.isEnable(sku.getStatus())
                    && StrUtil.isNotEmpty(oldCardKeyProductNo) && !oldCardKeyProductNo.equals(cardKeyProductNo)) {
                log.warn("上架状态的商品不可修改已经关联的卡密, cardKeyProductNo = {}, oldCardKeyProductNo = {}", cardKeyProductNo, oldCardKeyProductNo);
                throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "上架状态的商品不可修改已经关联的卡密");
            }
        }

        if (createReqVO.getCustomDenomination()) {
            // 自定义面值
            checkCustomDenomination(createReqVO, cardKeyProductNo, cardKeyProduct);
        } else {
            // 固定面额
            checkFixedDenomination(createReqVO, cardKeyProductNo, cardKeyProduct);
        }
        return cardKeyProduct;
    }

    private static void checkFixedDenomination(ProductSkuSaveReqV2VO createReqVO, String cardKeyProductNo, CardkeyProductDTO cardKeyProduct) {
        if (createReqVO.getMinCustomDenomination() != null) {
            log.warn("固定面值的时候不能设置最小面值, cardKeyProductNo = {}", cardKeyProductNo);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "固定面值的时候不能设置最小面值");
        }
        if (createReqVO.getMaxCustomDenomination() != null) {
            log.warn("固定面值的时候不能设置最大面值, cardKeyProductNo = {}", cardKeyProductNo);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "固定面值的时候不能设置最大面值");
        }

        final Integer denominationFixed = createReqVO.getDenominationFixed();
        if (!cardKeyProduct.getCustomDenomination()) {
            // 卡密是固定面值
            if (!denominationFixed.equals(cardKeyProduct.getDenominationFixed())) {
                log.warn("SKU的固定面值必须跟卡密的固定面值相等, cardKeyProductNo = {}, denominationFixed = {}, denominationFixed2 = {}",
                        cardKeyProductNo, denominationFixed, cardKeyProduct.getDenominationFixed());
                throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "SKU的固定面值必须跟卡密的固定面值相等");
            }
        } else {
            // 卡密是自定义面值
            if (denominationFixed < cardKeyProduct.getDenominationMin()) {
                log.warn("不符合该卡密商品规定的最小面值, cardKeyProductNo = {}, denominationFixed = {}, denominationMin = {}",
                        cardKeyProductNo, denominationFixed, cardKeyProduct.getDenominationMin());
                throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "不符合该卡密商品规定的最小面值");
            }

            if (denominationFixed > cardKeyProduct.getDenominationMax()) {
                log.warn("不符合该卡密商品规定的最大面值, cardKeyProductNo = {}, denominationFixed = {}, denominationMax = {}",
                        cardKeyProductNo, denominationFixed, cardKeyProduct.getDenominationMax());
                throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "不符合该卡密商品规定的最大面值");
            }
        }

        // 售价不能低于固定面值
//        final Integer price = createReqVO.getPrice();
//        if (price < denominationFixed) {
//            log.warn("售价不能低于固定面值, price = {}, denominationFixed = {}", price, denominationFixed);
            //throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "售价不能低于固定面值");
//        }
    }

    private DeliveryMethodEnum checkBasicNullValue(ProductSkuSaveReqV2VO createReqVO) {
        ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "deliveryMethod");// 发货方式
        ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "denomination"); // 面值
        ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "customDenomination"); // 是否自定义面值

        final DeliveryMethodEnum deliveryMethodEnum = DeliveryMethodEnum.fromValue(createReqVO.getDeliveryMethod());
        if (createReqVO.getCustomDenomination()) {
            // 自定义面值
            ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "minCustomDenomination"); // 最小自定义面值
            ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "maxCustomDenomination"); // 最大自定义面值
        } else {
            // 固定面值
            ProductUtil.checkFieldNullable(createReqVO.getId(), createReqVO, "denominationFixed"); // 固定面值
        }

        final Integer price = createReqVO.getPrice();
        if (price <= 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "销售价格不能小于等于0");
        }

        return deliveryMethodEnum;
    }

    private static void checkCustomDenomination(ProductSkuSaveReqV2VO createReqVO, String cardKeyProductNo, CardkeyProductDTO cardKeyProduct) {
        if (createReqVO.getDenominationFixed() != null) {
            log.warn("自定义面值的时候不能设置固定面值, cardKeyProductNo = {}", cardKeyProductNo);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "自定义面值的时候不能设置固定面值");
        }

        if (!cardKeyProduct.getCustomDenomination()) {
            log.warn("自定义面额的SKU无法关联固定面额的卡密商品, cardKeyProductNo = {}", cardKeyProductNo);
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, String.format("自定义面额的SKU无法关联固定面额的卡密商品 [%s]", cardKeyProductNo));
        }

        final Integer minCustomDenomination = createReqVO.getMinCustomDenomination();
        if (minCustomDenomination < cardKeyProduct.getDenominationMin()) {
            log.warn("不符合该卡密商品规定的最小面值, cardKeyProductNo = {}, minCustomDenomination = {}, denominationMin = {}",
                    cardKeyProductNo, minCustomDenomination, cardKeyProduct.getDenominationMin());
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "不符合该卡密商品规定的最小面值");
        }

        final Integer maxCustomDenomination = createReqVO.getMaxCustomDenomination();
        if (maxCustomDenomination > cardKeyProduct.getDenominationMax()) {
            log.warn("不符合该卡密商品规定的最大面值, cardKeyProductNo = {}, maxCustomDenomination = {}, denominationMax = {}",
                    cardKeyProductNo, maxCustomDenomination, cardKeyProduct.getDenominationMax());
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "不符合该卡密商品规定的最大面值");
        }

        final Integer price = createReqVO.getPrice();
        if (price < minCustomDenomination) {
            log.warn("售价不能低于最小面值, price = {}, minCustomDenomination = {}", price, minCustomDenomination);
            //throw ServiceExceptionUtil.exception(ErrorCodeConstants.SPU_FIELD_DEFAULT_ERROR, "售价不能低于最小面值");
        }
    }


}
